#include "glwidget.h"

GlWidget::GlWidget(QWidget * fatherWidget)
{
    isMoving=0;
    setParent(fatherWidget);
    setGeometry(0, 0, 500, 500);
}

void GlWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(isMoving==0)
    {
        anchorX=0;
        anchorY=0;
    }

    isMoving=1;

    ((TrackView *)View::MainView)->RotateView(anchorX - e->x(), anchorY- e->y());

    anchorX=e->x();
    anchorY=e->y();

    this->updateGL();
}

void GlWidget::wheelEvent(QWheelEvent *event)
 {
    ((TrackView *)View::MainView)->Zoom(event->delta()*0.05);
    this->updateGL();
     event->accept();

 }

void GlWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if(e->button()== Qt::LeftButton)
    {
        isMoving=0;
    }
}

void GlWidget::SetOpenGLVersion(int major, int minor)
{
    QGLFormat *  qglformat = new QGLFormat();
    qglformat->setVersion(major, minor);
    QGLFormat::setDefaultFormat(*qglformat);
}

void GlWidget::initializeGL()
{
    // First, I set initialize the window for opengl 3.1 version
    SetOpenGLVersion(3,1);

    // Then, I fire the init method of application
    Application::Init();

    // I create a new GLSLProgram for the application
    GLSLProgram::New("Default", new Shader(GL_FRAGMENT_SHADER,"basique.frag"), new Shader(GL_VERTEX_SHADER,"basique_2D.vert"));

    //	Here I create a New entity, wich would automaticaly be added to Entity::Entities

    Entity::New( Mesh::NewRect(1.0, 1.0));

    Entity::Last().m_Mesh->m_Image = new Image("mov.png");
    Entity::Last().m_Mesh->m_Image->GenTexture();
    Entity::Last().m_GLSLProgram    =   GLSLProgram::Programs.at(0)->m_GLID;

    Entity::New( Mesh::NewRect(1.0, 1.0));

    Entity::Last().m_Transform.Translate(1.0, 0.0, 0.0);
    Entity::Last().m_GLSLProgram    =   GLSLProgram::Programs.at(0)->m_GLID;

    new TrackView();

    Heightmap *     hm    =   new Heightmap();
    double size = pow(2,1);
    int sizeGrid = size + 1;

    hm->GenerateLandscape(sizeGrid);
    Entity::Last().m_GLSLProgram    =   GLSLProgram::Programs.at(0)->m_GLID;
}

void GlWidget::paintGL()
{
    Application::UpdateEntities();
    Application::UpdateDisplay();
}

void GlWidget::resizeGL(int w, int h)
{
     glViewport(0, 0, (GLint)w, (GLint)h);
}
